﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using DotNet.Utilities;
using KingRoad.EPM.Web.Util;
using KingRoad.EPM.Web.Areas.PersonnelLog;
using Unis.Framework.Core.Data;
using Unis.Framework.Core.Infrastructure;
using KingRoad.EPM.Web.Areas.PersonnelLog.PersonnelLogFramework.Mvc;

namespace KingRoad.EPM.Web
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new Util.Filter.AuthorizeFilter());// 自定义权限过滤器 ThinkWang 2014-2-27
            filters.Add(new HandleErrorAttribute { View = "MyCustomError" });
            //filters.Add(new HandleErrorAttribute());
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            try
            { //解决flash上传控件 无法传递 session问题 ThinkWang 2015-1-28
                string cookieName = "ASP.NET_SessionId";
                string cookieValue = Request.Form[cookieName];
                if (!string.IsNullOrEmpty(cookieValue))
                {
                    HttpCookie hc = Request.Cookies.Get(cookieName);
                    if (null == hc)
                        hc = new HttpCookie(cookieName);
                    hc.Value = cookieValue;
                    Request.Cookies.Set(hc);
                }
            }
            catch (Exception)
            {

                throw;
            }

        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.([iI][cC][oO]|[gG][iI][fF])(/.*)?" });
           

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parametersKingRoad.KingRoad.EPM.Common.Configuration.Settings.Instance.defaultpage
                new { controller = "Login"/*KingRoad.EPM.Common.Configuration.Settings.Instance.defaultpage*/, action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

        }

        protected void Application_Start()
        {
            #region 紫光Ioc依赖解析初始化
            // IOC初始化
            EngineContext.Initialize(false);
            // 数据库是否初始化
            bool databaseInstalled = DataSettingsHelper.DatabaseIsInstalled();
            // 定义Controllers实例化获取方法（通过IOC获取）
            DependencyResolver.SetResolver(new KingRoadPersonnelLogDependencyResolver());
            #endregion

            //aspose 注册
            //KingRoad.EMP.LicenseHelper.ModifyInMemory.ActivateMemoryPatching();
            #region 权限配置
            // 是否检查在线状态
            BaseSystemInfo.CheckOnLine = false;
            //BaseSystemInfo.AllowNullPassword = true;
            BaseSystemInfo.AutoLogOn = true;
            // 是否记录日志
            BaseSystemInfo.RecordLog = true;
            // 是否加密密码
            //BaseSystemInfo.EncryptPassword = true;
            // 是否需要注册
            BaseSystemInfo.NeedRegister = false;
            //读取权限的配置文件
            ConfigurationHelper.GetConfig();
            //UserConfigHelper.GetConfig(System.Web.HttpContext.Current.Server.MapPath(@"~/PermissionConfig.xml"));
            #endregion

            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
            //依赖注入
            //ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
        }

        protected void Application_Error(object sender, EventArgs e)
        {

            if (!HttpContext.Current.IsCustomErrorEnabled)
            {

                return;

            }



            var exception = Server.GetLastError();

            var httpException = new HttpException(null, exception);



            var routeData = new RouteData();

            routeData.Values.Add("controller", "Error");

            routeData.Values.Add("action", "Index");

            routeData.Values.Add("httpException", httpException);
            routeData.Values.Add("msg", exception.Message);


            Server.ClearError();



            var errorController = ControllerBuilder.Current.GetControllerFactory().CreateController(

                new RequestContext(new HttpContextWrapper(Context), routeData), "Error");



            errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));

        }
    }
}